import React, {useMemo, useState, useCallback} from 'react';
import {
  View,
  // Button,
  Text,
  // ScrollView,
  FlatList,
  ListRenderItemInfo,
  StyleSheet,
  NativeSyntheticEvent,
  NativeScrollEvent,
} from 'react-native';
import {RootStackNavigation} from '@/navigator/index';
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from '@/models/index';
import Carousel, {slidHeight} from './Carousel';
import Guess from './Guess';
import ChannelItem from './ChannelItem';
import {IChannel} from './../../models/home';
import {RouteProp} from '@react-navigation/native';
import {HomeParamList} from '@/navigator/HomeTabs';
import {IGuess} from '@/models/home';
const mapStateToProps = (
  state: RootState,
  {route}: {route: RouteProp<HomeParamList, string>},
) => {
  const {namespace} = route.params;
  const modelState = state[namespace];
  return {
    namespace,
    home: modelState,
    loading: state.loading.effects[`${namespace}/fetchChannel`],
  };
};
const connector = connect(mapStateToProps);
type modelState = ConnectedProps<typeof connector>; //获取redux中数据的模型以供给组件方便调用
interface IProps extends modelState {
  navigation: RootStackNavigation; //获取跳转路由之类参数
}

const Home = (props: IProps) => {
  const [refreshing, setRefreshing] = useState(false); // 决定是否展示下拉刷新动画
  const {home, dispatch, loading, namespace, navigation} = props;
  const {channels} = home;
  // useEffect(() => {
  //   dispatch({
  //     type: namespace + '/fetchCarousels',
  //   });
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, []);
  // let goAlbum = (data: IChannel) => {
  //   console.log(data);
  //   navigation.navigate('Album');
  // };
  let goAlbum = useCallback(
    (data: IChannel | IGuess) => {
      console.log(data);
      navigation.navigate('Album', {
        item: data,
      });
    },
    [navigation],
  );
  // FlatList没一项数据展示组件
  let channelsRenderItem = ({item}: ListRenderItemInfo<IChannel>) => {
    return <ChannelItem data={item} onPress={goAlbum} />;
  };
  // FlatList中每一项key值（便于diff）
  const keyExtractor = (item: IChannel) => {
    return item.id;
  };
  // FlatList触底加载事件
  const onEndReached = () => {
    const {hasMore} = home.pagination;
    if (loading || !hasMore) return;
    dispatch({
      type: namespace + '/fetchChannel',
      payload: {
        loadMore: true,
      },
    });
  };
  // FlatList下拉刷新事件
  const onRefresh = () => {
    // 开始下拉刷新动画
    setRefreshing(true);
    dispatch({
      type: namespace + '/fetchChannel',
      callback: () => {
        // 结束下拉刷新动画
        setRefreshing(false);
      },
    });
  };
  // FlatList底部展示组件
  const footer = useMemo(() => {
    const {pagination} = home;
    const {hasMore} = pagination;
    if (!hasMore) {
      return (
        <View style={styles.end}>
          <Text>--我是有底线的--</Text>
        </View>
      );
    }
    if (loading && channels.length > 0) {
      return (
        <View style={styles.loading}>
          <Text>--正在加载--</Text>
        </View>
      );
    }
  }, [channels.length, home, loading]);
  // const footer = () => {
  //   const {pagination} = home;
  //   const {hasMore} = pagination;
  //   if (!hasMore) {
  //     return (
  //       <View style={styles.end}>
  //         <Text>--我是有底线的--</Text>
  //       </View>
  //     );
  //   }
  //   if (loading && channels.length > 0) {
  //     return (
  //       <View style={styles.loading}>
  //         <Text>--正在加载--</Text>
  //       </View>
  //     );
  //   }
  // };
  // FlatList数据为空时展示组件
  const empty = useMemo(() => {
    if (loading) {
      return <View></View>;
    }
    return (
      <View style={styles.empty}>
        <Text>暂无数据</Text>
      </View>
    );
  }, [loading]);
  // const empty = () => {
  //   if (loading) {
  //     return <View></View>;
  //   }
  //   return (
  //     <View style={styles.empty}>
  //       <Text>暂无数据</Text>
  //     </View>
  //   );
  // };
  // FlatList顶部展示组件
  const header = useMemo(() => {
    return (
      <View>
        <Carousel />
        <View style={styles.background}>
          <Guess namespace={namespace} goAlbum={goAlbum} />
        </View>
      </View>
    );
  }, [goAlbum, namespace]);
  // 监听FlatList滚动事件
  /**
   * @param param0 nativeEvent 为原生事件  NativeSyntheticEvent<NativeScrollEvent>
   */
  const onScroll = ({nativeEvent}: NativeSyntheticEvent<NativeScrollEvent>) => {
    const offsetY = nativeEvent.contentOffset.y; // 拿到y轴偏移值
    const {gradientVisible} = home;
    let newGradientVisible = offsetY < slidHeight;
    if (newGradientVisible !== gradientVisible) {
      dispatch({
        type: namespace + '/setState',
        payload: {
          gradientVisible: newGradientVisible,
        },
      });
    }
  };
  return (
    <View>
      <FlatList
        ListHeaderComponent={header} // 顶部组件
        ListEmptyComponent={empty} // 为空时的展示
        data={channels} // 循环数据
        renderItem={channelsRenderItem} // 循环展示的每一项组件参数中的item为数据
        keyExtractor={keyExtractor} // 循环中每一项的key 参数中同样item为数据  返回值为key
        onRefresh={onRefresh} // 下拉刷新事件
        refreshing={refreshing} // 下拉刷新动画是否显示（一般在完成数据请求后置为false）
        onEndReached={onEndReached} //滑动到底部事件
        onEndReachedThreshold={0.2} //距离底部触发底部onEndReached事件比例
        ListFooterComponent={footer} //底部组件
        onScroll={onScroll} //监听滚动事件
      />
    </View>
    // <ScrollView>
    //   <Carousel data={carousels} />
    //   <Guess />
    // </ScrollView>
  );
};
const styles = StyleSheet.create({
  end: {
    alignItems: 'center',
    paddingVertical: 10,
  },
  loading: {
    alignItems: 'center',
    paddingVertical: 10,
  },
  empty: {
    alignItems: 'center',
    paddingVertical: 100,
  },
  background: {
    backgroundColor: '#FFF',
  },
});

export default connector(Home);
